
const http = ({ url, method = 'post', data, headers = {}, onProgress = e => e, requestList = [] }) => {
  return new Promise((resolve, reject) => {

    const xhr = new XMLHttpRequest()
    // 需要监听 upload.onprogress 进行上传进度监听
    xhr.upload.onprogress = onProgress
    xhr.open(method, url)
    Object.keys(headers).forEach(key => {
      xhr.setRequestHeader(key, headers[key])
    })
    xhr.send(data)
    xhr.onload = e => {
      // 将请求成功的xhr从列表删除
      if (requestList.length) {
        const xhrIndex = requestList.findIndex(e => e === xhr)
        requestList.splice(xhrIndex, 1)
      }
      if (xhr.readyState === 4 && xhr.status === 200) {
        resolve({
          data: e.target.response,
        })
      } else {
        reject({
          data: e.target.response,
        })
      }

    }
    requestList.push(xhr)
  })
}
export {
  http
}